<template>
    <el-main class="trifurcate-meter-page">
      <el-row :gutter="24" class="card-container">
  
        <!-- 表卡片 -->
        <el-col
          :span="6"
          v-for="meter in filteredMeters"
          :key="meter.meterId"
          class="card-col"
        >
          <el-card class="meter-card" shadow="hover">
            <div class="card-header">
              <h3>{{ meter.alias }}</h3>
            </div>
            
            <div class="card-body">
              <el-descriptions :column="1" border class="meter-value">
                <el-descriptions-item label="识别结果">
                  <span :class="{ 'no-data': !meter.aiValue }">
                    {{ meter.aiValue ? `${meter.aiValue} ${meter.unit}` : '暂无数据' }}
                  </span>
                </el-descriptions-item>
              </el-descriptions>
            </div>
  
            <div class="card-footer">
              <el-button type="primary" size="large" @click="openDetailDialog(meter)">详细</el-button>
  <!--            <el-button type="success" size="large" @click="openEditDialog(meter)">编辑</el-button>-->
            </div>
          </el-card>
        </el-col>
  
        <!-- 新增卡片 -->
        <el-col :span="6" class="card-col">
          <el-card class="add-card" @click="openCreateDialog">
            <div class="add-icon">+</div>
          </el-card>
        </el-col>
      </el-row>
  
      <!-- 弹窗组件 -->
      <EditDialog
        :visible="editDialogVisible"
        :alias="selectedMeter.alias"
        @save="updateAlias"
        @close="closeEditDialog"
      />
  
      <DetailDialog
        :visible="detailDialogVisible"
        :meterId="selectedMeter.meterId"
        :alias="selectedMeter.alias"
        :unit="selectedMeter.unit"
        :AiRes="JSON.stringify(selectedMeter.aiValue)"
        :imgRes="selectedMeter.image_path"
        :type="currentType"
        :monitorId="selectedMeter.monitorId"
        @update:visible="detailDialogVisible = $event"
        @update:AiRes="updateAiRes"
        @update:imgRes="updateImgRes"
        @refresh="fetchAllMeters"
      />
  
      <CreateMeterDialog
        :visible="createDialogVisible"
        :type="currentType"
        @update:visible="createDialogVisible = $event"
        @create="handleCreateMeter"
      />
    </el-main>
  </template>
  
  <script>
  import SearchBar from "../components/SearchBar.vue";
  import EditDialog from "../components/EditDialog.vue";
  import DetailDialog from "../components/DetailDialog.vue";
  import CreateMeterDialog from "../components/CreateMeterDialog.vue";
  import {
    getAllMeters,
    updateMeterAlias,
    getMeterDetails,
    createTrifurcateMeter
  } from "../api/meter";
  
  export default {
    name: "TrifurcateMeter",
    components: {
      SearchBar,
      EditDialog,
      DetailDialog,
      CreateMeterDialog
    },
    data() {
      return {
        meters: [],
        filteredMeters: [],
        editDialogVisible: false,
        detailDialogVisible: false,
        createDialogVisible: false,
        selectedMeter: {},
        currentType: "TrifurcateMeter"
      };
    },
    methods: {
      updateFilteredMeters(data) {
        this.filteredMeters = data;
      },
      //刷新之后更新数据
      updateAiRes(newAiRes) {
        this.selectedMeter.aiValue = newAiRes; // 更新父组件的数据
        this.selectedMeter.AiRes = JSON.stringify(newAiRes); // 确保父组件的 AiRes 属性也是更新的
      },
      updateImgRes(newImgRes) {
        this.selectedMeter.image_path = newImgRes; // 更新父组件的数据
        this.selectedMeter.imgRes = newImgRes; // 确保父组件的 imgRes 属性也是更新的
      },
      // 初始化数据
      async fetchAllMeters() {
        try {
          const response = await getAllMeters(this.currentType);
          const data=response.data;
  
          // 检查 data 是否为数组，如果不是，则尝试将其转换为数组
          this.meters = Array.isArray(data) ? data : [data];
          this.filteredMeters = [...this.meters]; // 使用扩展操作符复制数组
          console.log("获取的数据是",this.meters)
        } catch (error) {
          this.$message.error("获取数据失败");
          console.log(error);
        }
      },
  
      // 编辑功能
      async updateAlias(newAlias) {
        try {
          await updateMeterAlias(this.selectedMeter.meterID, newAlias);
          const meterIndex = this.meters.findIndex(
              (meter) => meter.meterID === this.selectedMeter.meterID
          );
          if (meterIndex !== -1) {
            this.meters[meterIndex].alias = newAlias;
            this.filteredMeters = [...this.meters];
          }
          this.$message.success("更新成功");
          this.closeEditDialog();
        } catch (error) {
          this.$message.error("更新失败");
        }
      },
  
      // 弹窗控制
      openEditDialog(meter) {
        this.selectedMeter = { ...meter };
        this.editDialogVisible = true;
      },
      closeEditDialog() {
        this.editDialogVisible = false;
      },
      //详情弹窗
      async openDetailDialog(meter) {
        this.selectedMeter = {...meter};
        this.detailDialogVisible = true;
        
        try {
          const details = await getMeterDetails(meter.meterId, this.currentType);
          if (details && details.data) {
            // 确保数据正确赋值
            this.selectedMeter = {
              ...this.selectedMeter,
              ...details.data,
              aiValue: details.data.aiValue,
              image_path: details.data.image_path
            };
            console.log("获取的详情数据:", this.selectedMeter);
          }
        } catch (error) {
          this.$message.error('获取详情失败');
          console.error("获取详情失败", error);
        }
      },
  
  
      openCreateDialog() {
        this.createDialogVisible = true;
      },
  
      // 创建新表
      async handleCreateMeter(meterData) {
        try {
          const createdMeter = await createTrifurcateMeter(
            meterData.alias,
            meterData.type,
            meterData.range,
            meterData.unit
          );
          
          // 创建成功后直接刷新数据
          await this.fetchAllMeters();
          
          this.$message.success("创建成功");
          this.createDialogVisible = false;
        } catch (error) {
          console.error("创建失败:", error);
          this.$message.error("创建失败");
        }
      }
    },
    async mounted() {
      await this.fetchAllMeters();
    }
  };
  </script>
  
  <style scoped>
  .trifurcate-meter-page {
    padding: 24px;
    background-color: var(--el-bg-color-page);
  }
  
  .card-container {
    max-width: 1400px;
    margin: 0 auto;
  }
  
  .card-col {
    margin-bottom: 24px;
  }
  
  .meter-card {
    height: 250px;
    transition: all 0.3s;
    display: flex;
    flex-direction: column;
  }
  
  .meter-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
  
  .card-header {
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
  
  .card-header h3 {
    margin: 0;
    font-size: 18px;
    color: var(--el-text-color-primary);
    text-align: center;
    font-weight: 500;
  }
  
  .card-body {
    padding: 20px;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .meter-value {
    margin: 0 auto;
    width: 200px;
  }
  
  .meter-value :deep(.el-descriptions) {
    width: 100%;
  }
  
  .meter-value :deep(.el-descriptions__cell) {
    padding: 0;
  }
  
  .meter-value :deep(.el-descriptions__label) {
    background-color: var(--el-fill-color-light);
    font-size: 14px;
    color: var(--el-text-color-regular);
    padding: 6px 10px;
    text-align: center;
    width: 120px;
    white-space: nowrap !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
  }
  
  .meter-value :deep(.el-descriptions__content) {
    text-align: center;
    padding: 6px 10px;
    font-size: 16px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 80px;
  }
  
  .meter-value span {
    font-size: 14px !important;
    font-weight: 500 !important;
    color: var(--el-text-color-primary) !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
    white-space: nowrap !important;
    display: block !important;
    max-width: 100% !important;
    line-height: 1.4 !important;
  }
  
  .meter-value span.no-data {
    font-size: 14px !important;
    color: var(--el-text-color-secondary) !important;
    font-weight: normal !important;
  }
  
  .card-footer {
    padding: 16px;
    border-top: 1px solid var(--el-border-color-lighter);
    display: flex;
    justify-content: center;
    gap: 16px;
  }
  
  .card-footer :deep(.el-button) {
    min-width: 90px;
    padding: 12px 20px;
    font-size: 14px;
    font-weight: 500;
  }
  
  .add-card {
    width: 100%;
    height: 250px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border: 2px dashed var(--el-color-primary);
    background-color: var(--el-bg-color);
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
  }
  
  .add-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border-color: var(--el-color-primary-light-3);
  }
  
  .add-icon {
    font-size: 36px;
    color: var(--el-color-primary);
    font-weight: 300;
  }
  </style>
  